package com.climb.moive.framework.jdbc;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class SingleColumnRowMapper<T> implements RowMapper<T> {
    private Class<?> requiredType;

    public SingleColumnRowMapper(Class<T> requiredType) {
        this.requiredType = requiredType;
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        // 返回结果集中只允许有一列
        ResultSetMetaData rsmd = rs.getMetaData();
        // 获得结果集中的列数
        int nrOfColumns = rsmd.getColumnCount();
        if (nrOfColumns != 1) {
            throw new RuntimeException("ResultSet中有" + nrOfColumns + "列");
        }

        // 获取结果集中的值，把值转换为对应Java类型
        Object value;
        int index = 1;//只有一列
        // 这里只处理常见类型，其它都处理为Object
        if (String.class == requiredType) {
            value = rs.getString(index);
        } else if (boolean.class == requiredType || Boolean.class == requiredType) {
            value = rs.getBoolean(index);
        } else if (byte.class == requiredType || Byte.class == requiredType) {
            value = rs.getByte(index);
        } else if (short.class == requiredType || Short.class == requiredType) {
            value = rs.getShort(index);
        } else if (int.class == requiredType || Integer.class == requiredType) {
            value = rs.getInt(index);
        } else if (long.class == requiredType || Long.class == requiredType) {
            value = rs.getLong(index);
        } else if (float.class == requiredType || Float.class == requiredType) {
            value = rs.getFloat(index);
        } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) {
            value = rs.getDouble(index);
        } else if (BigDecimal.class == requiredType) {
            value = rs.getBigDecimal(index);
        } else if (java.util.Date.class == requiredType) {
            value = new java.util.Date(rs.getDate(index).getTime());
        } else {
            throw new RuntimeException("不支持的类型" + requiredType);
        }

        return (T)value;
    }
}
